/*
 * Copyright (C) 2010 Moduad Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cc.telecomdigital.tdstock.activity.groups.more.push.client;

import java.io.IOException;
import java.util.Random;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.os.Vibrator;
import android.preference.RingtonePreference;
import android.provider.Settings;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.activity.RealtimeStockActivity;
import cc.telecomdigital.tdstock.activity.SplashActivity;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;

/**
 * This class is to notify the user of messages with NotificationManager.
 * 
 * @author hunter
 */
public class Notifier
{

	public static final int			SHOW_NOTIFICATION_SINGLE		= 0;
	public static final int			SHOW_NOTIFICATION_MULTIPL	= 1;								//default value;

	public static final String		NOTIFICATION_TITLE			= "響報通知";
	public static final String		NOTIFICATION_SINGLE_CONTENT	= "收到新的響報,目前共有%s條未讀取";
	public static final int			NOTIFICATION_SINGLE_ID		= 987654321;

	private static final String		TAG						= Notifier.class
																.getSimpleName();

	private static final Random		random					= new Random(
																System
																		.currentTimeMillis());

	private Context				context;

	private SharedPreferences		sharedPrefs;

	private static NotificationManager	notificationManager;

	public Notifier(Context context)
	{
		this.context = context;
		this.sharedPrefs = context.getSharedPreferences(
				Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
		notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
	}

	public void notify(String notificationId, String apiKey, String title,
			String message, String uri, String message_id,
			String messagetypeid)
	{

		TDStockLog.d(TAG, "notify()...");
		TDStockLog.d(TAG, "notificationId=" + notificationId);
		TDStockLog.d(TAG, "notificationApiKey=" + apiKey);
		TDStockLog.d(TAG, "notificationTitle=" + title);
		TDStockLog.d(TAG, "notificationMessage=" + message);
		TDStockLog.d(TAG, "notificationUri=" + uri);
		TDStockLog.d(TAG, "message_id=" + message_id);
		TDStockLog.d(TAG, "stock_id=" + messagetypeid);

		NotifierCounter.getInstnace().addCounter();
		/*获取是否提醒*/
		if (isNotificationEnabled())
		{
			// Show the toast
			/*
			 * if (isNotificationToastEnabled()) { Toast.makeText(context,
			 * message, Toast.LENGTH_LONG).show(); }
			 */

			// Notification
			Notification notification = new Notification();
			notification.icon = getNotificationIcon();
			/* 有声音和震动提醒 */
			if (isNotificationSoundEnabled()
					&& isNotificationVibrateEnabled())
			{
				notification.sound = android.net.Uri
						.parse(sharedPrefs
								.getString(
										CommonDefn.PREFERENCE_NOTIFICATION_RINGTONG,
										Settings.System.DEFAULT_NOTIFICATION_URI
												.toString()));
				long[] vibrate = { 0, 100, 200, 300 };
				notification.vibrate = vibrate;
			}
			//只有声音提醒
			else if (isNotificationSoundEnabled()
					&& !isNotificationVibrateEnabled())
			{
				notification.sound = android.net.Uri
						.parse(sharedPrefs
								.getString(
										CommonDefn.PREFERENCE_NOTIFICATION_RINGTONG,
										Settings.System.DEFAULT_NOTIFICATION_URI
												.toString()));
				//notification.defaults = Notification.DEFAULT_SOUND;
			}
			//只有震动提醒
			else if (isNotificationVibrateEnabled()
					&& !isNotificationSoundEnabled())
			{
				long[] vibrate = { 0, 100, 200, 300 };
				notification.vibrate = vibrate;
				//notification.defaults = Notification.DEFAULT_VIBRATE;
			}
			//声音和震动都没有
			else if (!isNotificationSoundEnabled()
					&& !isNotificationVibrateEnabled())
			{
				notification.defaults = Notification.DEFAULT_LIGHTS;
			}
			//notification.defaults=Notification.DEFAULT_ALL;
			notification.flags |= Notification.FLAG_AUTO_CANCEL;
			notification.when = System.currentTimeMillis();

			Intent intent = null;
			android.app.ActivityManager am = (android.app.ActivityManager) context
					.getSystemService(Context.ACTIVITY_SERVICE);
			ComponentName com = am.getRunningTasks(2).get(0).topActivity;

			String packageName = com.getPackageName();
			String className = com.getClassName();

			TDStockLog.d(TAG, String.format("packageName=%s ,className=%s",
					packageName, className));

			if (isMultipNotificationEnabled())
			{
				/**
				 * 判断单击通知转到 内容详细 列表
				 */
				TDStockLog.d(TAG, "message_id----------->" + message_id);
				if (null != message_id && message_id.trim().length() >= 1/*
																		 * &&!message_id
																		 * .
																		 * equals(" "
																		 * )
																		 */)
				{
					// new MessageThread(context,
					// message_id,MessageThread.NOT_LOGIN_CONTENT).start();
					// Data.id=message_id;
					if (com.getPackageName().equals(
							/*"cc.telecomdigital.tdstock"*/context
									.getPackageName()))
					{
						// 软件正在前台运行
						intent = new Intent(context,
								RealtimeStockActivity.class);
						intent.putExtra(Constants.INTENT_KEY_MESSAGE_ID,
								message_id);
						intent.putExtra(
								Constants.INTENT_KEY_MESSAGE_TYPE_ID,
								messagetypeid);
						// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						/*
						 * if(RealtimeStockActivity.tabHost!=null&&RealtimeStockActivity
						 * .tabHost.getCurrentTab()!=4){
						 * Constants._isGo_MoreActivity=true; }else{
						 * Constants._isSettingCurructTabMoreActivity=true; }
						 * Abstract_ActivityController.IsCurrentActivity=true;
						 * Constants._isGO_MessageContentActivity_Immediately=true;
						 * Constants
						 * ._isGo_MessageHistoryListActivity_Immediately=true;
						 */

						if (RealtimeStockActivity.tabHost != null
								&& RealtimeStockActivity.tabHost
										.getCurrentTab() != 4)
						{
							// Constants._isGo_MoreActivity=true;
							intent
									.putExtra(
											Constants.INTENT_KEY_ISGO_MOREACTIVITY,
											true);
						}
						else
						{
							// Constants._isSettingCurructTabMoreActivity=true;
							intent
									.putExtra(
											Constants.INTENT_KEY_ISSETTING_CURRUCT_TABMOREACTIVITY,
											true);
						}

						/*
						 * Abstract_ActivityController.IsCurrentActivity=true;
						 * Constants._isGO_MessageContentActivity_Immediately=true;
						 * Constants
						 * ._isGo_MessageHistoryListActivity_Immediately=true;
						 */
					}
					else
					{
						intent = new Intent(context, SplashActivity.class);// 软件关闭，后台运行service
						//Constants._isGo_MoreActivity = true;
						// Constants._isGo_MessageHistoryListActivity=true;
						//Constants._isGO_MessageContentActivity = true;
						/*
						 * intent.putExtra(Constants.INTENT_KEY_ISGO_MOREACTIVITY,
						 * true); intent.putExtra(Constants.INTENT_KEY_MESSAGE_ID,
						 * message_id); intent.putExtra(Constants.
						 * INTENT_KEY_ISGO_MESSAGEHISTORYLISTACTIVITY_IMMEDIATELY,
						 * false); intent.putExtra(Constants.
						 * INTENT_KEY_ISGO_MESSAGECONTENTACTIVITY_IMMEDIATELY,
						 * true);
						 */
						//Data.id = message_id;
						intent.putExtra(Constants.INTENT_KEY_MESSAGE_ID,
								message_id);
						intent.putExtra(
								Constants.INTENT_KEY_MESSAGE_TYPE_ID,
								messagetypeid);
					}

				}
				/**
				 * 转到 List UI
				 */
				else if (null != message_id
						&& message_id.trim().length() <= 0)
				{
					// new MessageThread(context,"",MessageThread._LIST).start();
					if (com.getPackageName().equals(
							/*"cc.telecomdigital.tdstock"*/context
									.getPackageName()))
					{ // 软件正在前台运行
						intent = new Intent(context,
								RealtimeStockActivity.class);
						intent.putExtra(Constants.INTENT_KEY_MESSAGE_ID,
								"");
						intent.putExtra(
								Constants.INTENT_KEY_MESSAGE_TYPE_ID,
								"2");
						/*
						 * if(RealtimeStockActivity.tabHost!=null&&RealtimeStockActivity
						 * .tabHost.getCurrentTab()!=4){
						 * Constants._isGo_MoreActivity=true; }else{
						 * Constants._isSettingCurructTabMoreActivity=true; }
						 * Abstract_ActivityController.IsCurrentActivity=true;
						 * Constants
						 * ._isGo_MessageHistoryListActivity_Immediately=true;
						 */

						if (RealtimeStockActivity.tabHost != null
								&& RealtimeStockActivity.tabHost
										.getCurrentTab() != 4)
						{
							// Constants._isGo_MoreActivity=true;
							intent
									.putExtra(
											Constants.INTENT_KEY_ISGO_MOREACTIVITY,
											true);
						}
						else
						{
							// Constants._isSettingCurructTabMoreActivity=true;
							intent
									.putExtra(
											Constants.INTENT_KEY_ISSETTING_CURRUCT_TABMOREACTIVITY,
											true);
						}
						// Abstract_ActivityController.IsCurrentActivity=true;
						// Constants._isGo_MessageHistoryListActivity_Immediately=true;

					}
					else
					{ // 软件关闭，后台运行service
						//Constants._isGo_MoreActivity = true;
						//Constants._isGo_MessageHistoryListActivity = true;
						intent = new Intent(context, SplashActivity.class);
						intent.putExtra(Constants.INTENT_KEY_MESSAGE_ID,
								"");
						intent.putExtra(
								Constants.INTENT_KEY_MESSAGE_TYPE_ID,
								"2");
						// intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
					}
				}
				// Data.message_type_id=messagetypeid;
				int num = random.nextInt();
				TDStockLog.d(TAG, num + "");
				PendingIntent contentIntent = PendingIntent.getActivity(
						context, num, intent,
						PendingIntent.FLAG_UPDATE_CURRENT);
				notification.tickerText = title;
				// notification.contentView.setOnClickPendingIntent(1,
				// contentIntent);
				notification.setLatestEventInfo(context, title, message,
						contentIntent);
				notificationManager.notify(random.nextInt(), notification);
			}/* else {
				 有声音和震动提醒 
				if(isNotificationSoundEnabled()&&isNotificationVibrateEnabled()){
					 sound(context);
					 vibrate(context);
				}
				//只有声音提醒
				else if (isNotificationSoundEnabled()&&!isNotificationVibrateEnabled()) {
					 sound(context);
				}
				//只有震动提醒
				else if (isNotificationVibrateEnabled()&&!isNotificationSoundEnabled()) {
					vibrate(context);
				}
				else if(!isNotificationSoundEnabled()&&!isNotificationVibrateEnabled()){
					TDStockLog.w(TAG, "Notificaitons all disabled.");
				}
				
				}*/

			else
			{
				//single  notification appear in status bar

				if (com.getPackageName().equals(
						/*"cc.telecomdigital.tdstock"*/context
								.getPackageName()))
				{ // 软件正在前台运行
					intent = new Intent(context,
							RealtimeStockActivity.class);
					intent.putExtra(Constants.INTENT_KEY_MESSAGE_ID, "");
					intent.putExtra(Constants.INTENT_KEY_MESSAGE_TYPE_ID,
							"2");

					if (RealtimeStockActivity.tabHost != null
							&& RealtimeStockActivity.tabHost
									.getCurrentTab() != 4)
					{
						// Constants._isGo_MoreActivity=true;
						intent.putExtra(
								Constants.INTENT_KEY_ISGO_MOREACTIVITY,
								true);
					}
					else
					{
						// Constants._isSettingCurructTabMoreActivity=true;
						intent
								.putExtra(
										Constants.INTENT_KEY_ISSETTING_CURRUCT_TABMOREACTIVITY,
										true);
					}
					// Abstract_ActivityController.IsCurrentActivity=true;
					// Constants._isGo_MessageHistoryListActivity_Immediately=true;

				}
				else
				{ // 软件关闭，后台运行service

					intent = new Intent(context, SplashActivity.class);
					intent.putExtra(Constants.INTENT_KEY_MESSAGE_ID, "");
					intent.putExtra(Constants.INTENT_KEY_MESSAGE_TYPE_ID,
							"2");
				}

				PendingIntent contentIntent = PendingIntent.getActivity(
						context, 0, intent,
						PendingIntent.FLAG_UPDATE_CURRENT);
				notification.tickerText = title;
				// notification.contentView.setOnClickPendingIntent(1,
				// contentIntent);
				notification
						.setLatestEventInfo(context, NOTIFICATION_TITLE,
								String.format(
										NOTIFICATION_SINGLE_CONTENT,
										NotifierCounter.getInstnace()
												.getCounter()),
								contentIntent);
				notificationManager.notify(NOTIFICATION_SINGLE_ID,
						notification);

			}

		} //end  isNotificationEnabled

	}

	private int getNotificationIcon()
	{
		return sharedPrefs.getInt(Constants.NOTIFICATION_ICON, 0);
	}

	private boolean isNotificationEnabled()
	{
		return sharedPrefs.getBoolean(
				Constants.SETTINGS_NOTIFICATION_ENABLED, true);
	}

	private boolean isMultipNotificationEnabled()
	{
		return sharedPrefs.getInt(
				CommonDefn.PREFERENCE_NOTIFICATION_SHOW_TYPE_ID,
				SHOW_NOTIFICATION_MULTIPL) == SHOW_NOTIFICATION_MULTIPL;
	}

	private boolean isNotificationSoundEnabled()
	{
		//return sharedPrefs.getBoolean(Constants.SETTINGS_SOUND_ENABLED, true);
		return !sharedPrefs.getString(
				CommonDefn.PREFERENCE_NOTIFICATION_RINGTONG, "null")
				.equals("null");
	}

	private boolean isNotificationVibrateEnabled()
	{
		return sharedPrefs.getBoolean(Constants.SETTINGS_VIBRATE_ENABLED,
				true);
	}

	/*
	 * private boolean isNotificationToastEnabled() { return
	 * sharedPrefs.getBoolean(Constants.SETTINGS_TOAST_ENABLED, false); }
	 */
	public static void clearAllNotification()
	{
		if (notificationManager != null)
		{
			notificationManager.cancelAll();
		}
	}

	//开启震动
	public static void vibrate(Context context)
	{
		Vibrator v = (Vibrator) context
				.getSystemService(Context.VIBRATOR_SERVICE);
		v.vibrate(2200);
	}

	//播放铃声
	public static void sound(Context context)
	{
		MediaPlayer mMediaPlayer = new MediaPlayer();
		try
		{
			mMediaPlayer.setDataSource(context, RingtoneManager
					.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
			AudioManager audioManager = (AudioManager) context
					.getSystemService(Context.AUDIO_SERVICE);
			if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0)
			{
				mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
				mMediaPlayer.setLooping(false);
				mMediaPlayer.prepare();
				mMediaPlayer.start();
			}
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			TDStockLog.d(TAG, "sound is not play");
		}

	}
}
